package cn.it.xiaohan.note.web;

import cn.it.xiaohan.note.po.Note;
import cn.it.xiaohan.note.po.User;
import cn.it.xiaohan.note.service.NoteService;
import cn.it.xiaohan.note.util.JsonUtil;
import cn.it.xiaohan.note.vo.ResultInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@WebServlet("/report")
public class ReportServlet extends HttpServlet {

    private NoteService noteService = new NoteService();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置导航栏的高亮效果
        request.setAttribute("menu_page","report");

        // 获取用户行为
        String actionName = request.getParameter("actionName");

        // 判断用户行为
        if ("info".equals(actionName)){

            // 进入数据报表首页
            reportInfo(request,response);
        } else if ("month".equals(actionName)){

            // 通过月份查询云记数量
            queryNoteCountByMonth(request,response);
        } else if ("location".equals(actionName)){

            // 查询用户发布云记时的坐标
            queryNoteLonAndLat(request,response);
        }
    }

    /**
     * 查询用户发布云记时的坐标
     * @param request
     * @param response
     */
    private void queryNoteLonAndLat(HttpServletRequest request, HttpServletResponse response) {
        // 获取Session作用狱中的用户对象
        User user = (User) request.getSession().getAttribute("user");
        // 调用Service层的查询方法，返回ResultInfo对象
        ResultInfo<List<Note>> resultInfo = noteService.queryNoteLonAndLat(user.getUserId());
        // 将返回的resultInfo对象通过转换成JSON格式的字符串，响应给前台的Ajax函数
        JsonUtil.toJson(response,resultInfo);
    }

    /**
     * 通过月份查询云记数量
     * @param request
     * @param response
     */
    private void queryNoteCountByMonth(HttpServletRequest request, HttpServletResponse response) {
        // 获取Session中的用户对象
        User user = (User) request.getSession().getAttribute("user");
        // 调用Service层方法，返回resultInfo对象
        ResultInfo<Map<String,Object>> resultInfo = noteService.queryNoteCountByMonth(user.getUserId());
        // 将查询到的对象转换成JSON格式的字符传，响应给前台的Ajax回调函数
        JsonUtil.toJson(response,resultInfo);
    }

    /**
     * 进入数据报表首页
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void reportInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置动态包含的页面值
        request.setAttribute("changePage","report/info.jsp");
        // 请求转发到index.jsp
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }
}
